<?php

namespace App\Request\auth\Service\Auth;

use App\Repository\Auth\AdminRoleRepository;
use App\Repository\Auth\RoleRepository;
use App\Request\auth\Service\IService;


/**
 * 管理员角色分配表
 */
final class AdminRoleService extends IService
{
    public function __construct(
        protected readonly AdminRoleRepository $repository,
        protected readonly RoleRepository      $roleRepository,
    )
    {
    }


    /**
     * 创建管理员角色分配
     * @param int $admin_id
     * @param array $role_ids
     * @return bool
     */
    public function batchInsert(int $admin_id, array $role_ids): bool
    {
        if (empty($role_ids)) {
            return false;
        }
        $data = [];
        foreach ($role_ids as $role_id) {
            $data[] = [
                'admin_id' => $admin_id,
                'role_id' => $role_id,
            ];
        }
        //先删除之前的
        $this->repository->getQuery()->where('admin_id', $admin_id)->delete();
        return $this->repository->getQuery()->insert($data);
    }

    /**
     * 获取角色id
     * @param int $daminId
     * @return array
     */
    public function getRoleIdByAdminId(int $daminId): array
    {
        return $this->repository->getQuery()->where('admin_id', $daminId)->pluck('role_id')->toArray();
    }

    /**
     * 获取角色名
     * @param int $daminId
     * @return array|string
     */
    public function getRoleNameByRoleId(int $daminId): array|string
    {
        if ($daminId == 1) return '超级管理员';
        $RoleIds = $this->getRoleIdByAdminId($daminId);
        return $this->roleRepository->getQuery()->whereIn('id', $RoleIds)->pluck('name')->toArray();
    }


}